import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

import { CSSTransition, TransitionGroup } from 'react-transition-group';
// import { TransitionGroup } from 'react-transition-group';
// import Transition from '@/components/Transition/transition';

import Notification from './notification';

import styles from './index.less';
import './transition.less';
interface NotificationApi {
  info: (config: Notice) => void;
  success: (config: Notice) => void;
  warning: (config: Notice) => void;
  error: (config: Notice) => void;
}

type NotificationType = 'info' | 'success' | 'danger' | 'warning';

interface Notice {
  title: string;
  description: string;
  key?: string;
  type?: NotificationType;
}

let seed = 0;
const now = Date.now();
const getUuid = (): string => {
  const id = seed;
  seed += 1;
  return `notification_${now}_${id}`;
};

let add: (notice: Notice) => void;

const NotificationContainer = () => {
  const [notices, setNotices] = useState<Notice[]>([]);
  const timeout = 3 * 1000;
  const maxCount = 10;

  const remove = (notice: Notice) => {
    const { key } = notice;
    setNotices((prevNotices) => {
      return prevNotices.filter(({ key: itemKey }) => key !== itemKey);
    });
  };

  add = (notice: Notice) => {
    setNotices((prevNotices) => [...prevNotices, notice]);

    setTimeout(() => {
      remove(notice);
    }, timeout);
  };

  useEffect(() => {
    if (notices.length > maxCount) {
      const [firstNotice] = notices; //索引0的数据
      remove(firstNotice);
    }
  }, [notices]);
  return (
    <div className={styles.notificationContainer}>
      <TransitionGroup>
        {notices.map(({ title, description, key: itemKey, type = 'info' }) => (
          <CSSTransition key={itemKey} timeout={500} classNames="notices-item">
            <Notification
              itemKey={itemKey as string}
              type={type}
              title={title}
              description={description}
              onClose={(key) => {
                remove(notices.filter((item) => item.key === key)[0]);
              }}
            />
          </CSSTransition>
        ))}
      </TransitionGroup>
    </div>
  );
};

let el = document.querySelector('#notification-wrapper');
if (!el) {
  el = document.createElement('div');
  el.className = 'notification-wrapper';
  el.id = 'notification-wrapper';
  document.body.append(el);
}

ReactDOM.render(<NotificationContainer />, el);

const useApi = (config: Notice, type: NotificationType): void => {
  const { title, description } = config;
  add({
    title,
    description,
    key: getUuid(),
    type,
  });
};
const api: NotificationApi = {
  info: (config: Notice) => {
    useApi(config, 'info');
  },
  success: (config: Notice) => {
    useApi(config, 'success');
  },
  warning: (config: Notice) => {
    useApi(config, 'warning');
  },
  error: (config: Notice) => {
    useApi(config, 'danger');
  },
};

export default api;
